import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)
    // Vue.prototype.axios = axios

export default new Vuex.Store({
    state: {
        //所有任务列表
        list: [],
        //文本输入框中的值
        inputValue: 'AAA',
        activeIndex: 2
    },
    mutations: {
        initList(state, list) {
            state.list = list
        },
        setInputValue(state, value) {
            state.inputValue = value
        },

        // 同步inputValue
        addList(state) {
            state.list.push({
                id: state.nextId,
                info: state.inputValue.trim(),
                done: false
            })
            state.nextId++;
            state.inputValue = '';

        },

        // 删除数据
        moveList(state, id) {
            const index = state.list.findIndex(item => {
                return item.id === id
            })
            state.list.splice(index, 1)
        },

        // 改变复选框状态
        changeDone(state, id) {
            const index = state.list.findIndex(item => {
                return item.id === id
            })
            state.list[index].done = !state.list[index].done
        },

        // 清除已完成
        clearDone(state) {
            var unDone = state.list.filter(item => {
                return item.done == false
            })
            state.list = unDone
        },

        // 切换选项
        changeKey(state, key) {
            state.activeIndex = key
        }

    },
    actions: {
        async getList(context) {
            var data = await axios.get('/list.json').then(({ data }) => {
                console.log(data);
                context.commit('initList', data)
            })
        }
    },

    // 计算剩余项
    getters: {
        unDoneLength(state) {
            const temp = state.list.filter(item => {
                return item.done == false
            })
            return temp.length
        },

        // 切换不同选项,展示不同页面
        infoList(state) {
            if (state.activeIndex == 0) {
                return state.list
            }
            if (state.activeIndex == 1) {
                return state.list.filter(item => {
                    return item.done == false
                })
            }
            if (state.activeIndex == 2) {
                return state.list.filter(item => {
                    return item.done == true
                })
            }


        }
    }
})